//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Resource Application Block
//===============================================================================

using System;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Configuration.Design;
using Microsoft.Practices.EnterpriseLibrary.Data.Configuration.Design;

namespace EntLibContrib.Resource.Configuration.Design
{
	/// <summary>
	/// Represents the design manager for the database resource provider.
	/// </summary>
	public sealed class ResourceDatabaseConfigurationDesignManager : ConfigurationDesignManager
	{
		#region Public Methods
		/// <summary>
		/// Register the commands and node maps needed for the design manager into the design time.
		/// </summary>
		/// <param name="serviceProvider">The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</param>
    public override void Register(IServiceProvider serviceProvider)
    {
			DataResourceProviderNodeMapRegistrar nodeMapRegistrar = new DataResourceProviderNodeMapRegistrar(serviceProvider);
			nodeMapRegistrar.Register();
			DataResourceProviderCommandRegistrar commandRegistrar = new DataResourceProviderCommandRegistrar(serviceProvider);
      commandRegistrar.Register();
		}
		#endregion

		#region Protected Methods
		/// <summary>
		/// Initializes the data resource provider and adds it to the resource settings.
		/// </summary>
		/// <param name="serviceProvider">The mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</param>
		/// <param name="rootNode">The root node of the application.</param>
		/// <param name="section">The <see cref="ConfigurationSection"/> that was opened from the <see cref="IConfigurationSource"/>.</param>
		protected override void OpenCore(IServiceProvider serviceProvider, ConfigurationApplicationNode rootNode, ConfigurationSection section)
		{			
			// match connection string names with conection string nodes
			IConfigurationUIHierarchy hierarchy = ServiceHelper.GetCurrentHierarchy(serviceProvider);
			foreach (DataResourceProviderNode dataResourceProviderNode in hierarchy.FindNodesByType(typeof(DataResourceProviderNode)))
			{
				foreach (ConnectionStringSettingsNode connectionNode in hierarchy.FindNodesByType(typeof(ConnectionStringSettingsNode)))
				{
					if (connectionNode.Name == dataResourceProviderNode.connectionStringName)
					{
						dataResourceProviderNode.DatabaseInstance = connectionNode;
						break;
					}
				}
			}			
		}
		#endregion
	}
}
